﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBR.Common;
using TBR.Entities;

namespace TBR.Repositories
{
    public class GuestRepository
    {
        #region constructor
        public GuestRepository()
        {
            this.webhelper = new WebHelper();
            this.htmlhelper = new HtmlHelper();
            this.Guests = new List<User>();
        }
        #endregion

        #region events
        public delegate void RequestEventHandler(object source, RequestEventArgs args);
        public class RequestEventArgs : EventArgs
        {
            public IList<User> Guests;
        }
        #endregion

        #region GetGuestCompleted
        public event RequestEventHandler GetGuestCompleted;
        public void OnGetGuestCompleted()
        {
            if (GetGuestCompleted != null)
            {
                RequestEventArgs args = new RequestEventArgs();
                args.Guests = Guests;
                GetGuestCompleted(this, args);
            }
        }

        [Obsolete]
        private void webHelper_GetGuestCompleted(object sender, TBR.Common.WebHelper.RequestEventArgs args)
        {
            webhelper.RequestCompleted -= webHelper_GetGuestCompleted;
            List<string> strGuests = htmlhelper.GetDivCollections(args.HtmlCode, "Мои гости", "pages", "</div></div>", "<div>", HtmlHelper.Tag.TwoDivs).ToList();
            IList<User> guestssOnCurrentPage = ExtractGuests(strGuests);
            bool isPagesEnded = Guests.Any(u =>
            {
                foreach (var user in guestssOnCurrentPage)
                    if (user.Id == u.Id)
                        return true;
                return false;
            });

            if (isPagesEnded)
            {
                OnGetGuestCompleted();
            }
            else
            {
                foreach (var user in guestssOnCurrentPage)
                    Guests.Add(user);
                currentPage++;
                GetGuests(currentPage);

            }
        }
        private void webhelper_GetGuestsPageCompleted(object source, WebHelper.RequestEventArgs args)
        {
            webhelper.RequestCompleted -= webhelper_GetGuestsPageCompleted;
            List<string> strUsers = htmlhelper.GetDivCollections(args.HtmlCode, "Мои гости", "main.php", "</div></div>", "<div>").ToList();
            Guests = ExtractGuests(strUsers);
            OnGetGuestCompleted();
        }
        #endregion

        #region properties
        private WebHelper webhelper { get; set; }
        private HtmlHelper htmlhelper { get; set; }
        private string HtmlResponse { get; set; }
        private IList<User> Guests { get; set; }
        private int currentPage = 1;
        #endregion

        #region public methods
        public void GetGuests(int page = 1)
        {
            // webhelper.RequestCompleted += webHelper_GetGuestCompleted;
            webhelper.RequestCompleted += webhelper_GetGuestsPageCompleted;
            string sid = CookieHelper.GetPropertyCookieByKey("sid");
            webhelper.GetHtmlCode(new Uri(String.Format("http://tabor.ru/guests.php?p={0}&sid={1}", page, sid)), WebHelper.Method.Get);
        }

        #endregion

        #region private methods
        private IList<User> ExtractGuests(IList<string> strList)
        {
            var guests = new List<User>();
            foreach (var div in strList)
            {
                if (div.Contains("profile.php"))
                {
                    var guestName = GetName(div);
                    var id = GetId(div);
                    var sex = GetSex(div);
                    var imgUrl = GetImageUrl(div);
                    var age = GetAge(div);
                    var location = GetLocation(div);
                    var actionDate = GetActionDate(div);
                    guests.Add(new User(id, guestName, imgUrl, age, location, sex, actionDate));
                }
            }
            return guests;
        }

        private string GetName(string text)
        {
            text = text.Substring(0, text.IndexOf("</a>"));
            return text.Remove(0, text.LastIndexOf(">") + 1);
        }

        private string GetId(string text)
        {
            text = text.Remove(0, text.IndexOf("id=") + 3);
            return text.Substring(0, text.IndexOf("&amp;"));
        }

        private ESex GetSex(string text)
        {
            return text.IndexOf("boy.png") != -1 ? ESex.Male : ESex.Female;
        }

        private string GetImageUrl(string text)
        {
            string begin = "\"><img src=\"";
            text = text.Remove(0, text.LastIndexOf(begin) + begin.Length);
            return text.Remove(text.IndexOf('"'));
        }

        private int GetAge(string text)
        {
            string begin = "</a>, ";
            text = text.Remove(0, text.IndexOf(begin) + begin.Length);
            return int.Parse(text.Remove(text.IndexOf("</div>")));
        }

        private string GetLocation(string text)
        {
            string begin = "/></a></div><div>";
            text = text.Remove(0, text.IndexOf(begin) + begin.Length + 1);
            return text.Remove(text.IndexOf("<"));
        }
        private string GetActionDate(string text)
        {
            int startSpanIndex = text.IndexOf("<span");
            int endSpanIndex = text.IndexOf("span>");
            if (startSpanIndex != -1 && endSpanIndex != -1 && startSpanIndex < endSpanIndex)
            {
                string span = text.Substring(startSpanIndex, endSpanIndex - startSpanIndex);
                int startIndex = span.IndexOf(">") + 1;
                int endIndex = span.LastIndexOf("<");
                return span.Substring(startIndex, endIndex - startIndex);
            }
            else return String.Empty;
        }
        #endregion
    }
}
